package com.eh.test;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by David Li on 2016/5/19.
 * <p>
 * 在页面上显示文件
 */
@WebServlet("/showFile.do")
public class ShowFileServlet extends HttpServlet {
    private static String file_path = "/WEB-INF/img/test1.gif";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String mimeType = this.getServletContext().getMimeType(file_path);
        resp.setContentType(mimeType);
        InputStream in = this.getServletContext().getResourceAsStream(file_path);
        OutputStream out = resp.getOutputStream();
        output(in, out);
    }

    private void output(InputStream in, OutputStream out) {
        try (InputStream src = in; OutputStream dest = out) {
            byte[] buff = new byte[1024];
            while (src.read(buff) != -1) {
                dest.write(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
